package com.sjgtw.cloud.web.warningSign.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.warningSign.domain.WarningSigns;
import com.sjgtw.cloud.web.warningSign.mapper.WarningSignsMapper;
import com.sjgtw.cloud.web.warningSign.service.IWarningSignsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 防洪警示标志Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-11
 */
@Service
public class WarningSignsServiceImpl implements IWarningSignsService
{
    @Autowired
    private WarningSignsMapper warningSignsMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询防洪警示标志
     * 
     * @param id 防洪警示标志主键
     * @return 防洪警示标志
     */
    @Override
    public WarningSigns selectWarningSignsById(Long id)
    {
        return warningSignsMapper.selectWarningSignsById(id);
    }

    /**
     * 查询防洪警示标志列表
     * 
     * @param warningSigns 防洪警示标志
     * @return 防洪警示标志
     */
    @Override
    public  List<Map<String,Object>>  selectWarningSignsList(WarningSigns warningSigns)
    {
        return warningSignsMapper.selectWarningSignsList(warningSigns);
    }

    @Override
    public List<WarningSigns> selectWarningSignsList2(WarningSigns warningSigns) {
        return warningSignsMapper.selectWarningSignsList2(warningSigns);
    }

    /**
     * 新增防洪警示标志
     * 
     * @param warningSigns 防洪警示标志
     * @return 结果
     */
    @Override
    public int insertWarningSigns(WarningSigns warningSigns)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        warningSigns.setCreateTime(new Date());
        warningSigns.setCreateBy(user.getUsername());
        return warningSignsMapper.insertWarningSigns(warningSigns);
    }

    /**
     * 修改防洪警示标志
     * 
     * @param warningSigns 防洪警示标志
     * @return 结果
     */
    @Override
    public int updateWarningSigns(WarningSigns warningSigns)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        warningSigns.setUpdateBy(user.getUsername());
        warningSigns.setUpdateTime(new Date());
        return warningSignsMapper.updateWarningSigns(warningSigns);
    }

    /**
     * 批量删除防洪警示标志
     * 
     * @param ids 需要删除的防洪警示标志主键
     * @return 结果
     */
    @Override
    public int deleteWarningSignsByIds(Long[] ids)
    {
        return warningSignsMapper.deleteWarningSignsByIds(ids);
    }

    /**
     * 删除防洪警示标志信息
     * 
     * @param id 防洪警示标志主键
     * @return 结果
     */
    @Override
    public int deleteWarningSignsById(Long id)
    {
        return warningSignsMapper.deleteWarningSignsById(id);
    }

    @Override
    public List<String> check(List<WarningSigns> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (WarningSigns entity : entities) {
            if (StringUtils.isEmpty(entity.getSection())) {
                errors.add("序号为" + entity.getNum() + "行数据区段不能为空");
            } else if (deptMap.containsKey(entity.getSection())) {
                entity.setSectionId(deptMap.get(entity.getSection()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据区段不存在");
            }

            if (StringUtils.isEmpty(entity.getWorkArea())) {
                errors.add("序号为" + entity.getNum() + "行数据工区不能为空");
            } else if (deptMap.containsKey(entity.getWorkArea())) {
                entity.setWorkAreaId(deptMap.get(entity.getWorkArea()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据工区不存在");
            }
            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<WarningSigns> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<WarningSigns> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        warningSignsMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                warningSignsMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<WarningSigns> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (WarningSigns entity : entities) {
            uniqueNamesSet.add(entity.getSection());
            uniqueNamesSet.add(entity.getWorkArea());
        }

        return new ArrayList<>(uniqueNamesSet);
    }
}
